package com.example.demo.service;

import com.example.demo.entity.Person;
import com.example.demo.repository.PersonRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import javax.persistence.criteria.Predicate;

/**
 * Created by pengwan on 2017/7/30.
 */
@Service
public class PersonService {
    @Autowired
    private PersonRepository personRepository;
    public Page<Person> findBySpecAndPaginate(String city, double minWeight, String descOrderBy, int page, int size){

        Specification<Person> personSpecification = (root, criteriaQuery, criteriaBuilder) -> {
            Predicate predicateCity = criteriaBuilder.like(root.get("address").get("city"), city);
            Predicate predicateWeight = criteriaBuilder.ge(root.get("weight"), minWeight);
            Predicate predicate = criteriaBuilder.and(predicateCity, predicateWeight);
            criteriaQuery.where(predicate);
            //criteriaQuery.orderBy(criteriaBuilder.desc(root.get("birthday")));
            return criteriaQuery.getRestriction();
        };
        PageRequest pageRequest = new PageRequest(page, size, new Sort(Sort.Direction.DESC, descOrderBy));
        return this.personRepository.findAll(personSpecification,pageRequest);
    }
}
